package com.whut.handler;

import com.whut.domain.CreateParameter;
import com.whut.domain.Parameter;
import com.whut.service.AsyncOpenStackService;
import com.whut.util.SendMessageUtil;
import com.whut.wesocket.PollWebSocketServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Logger;

/**
 * Created by YY on 2018-01-31.
 */
@Service
public class AsyncMultiTaskHandler implements Runnable{

    protected static Logger logger=Logger.getLogger(String.valueOf(AsyncMultiTaskHandler.class));

    protected Parameter[] parameters;
    protected CreateParameter[] createParameters;
    protected String md5;
    private PollWebSocketServlet webSocketServlet;

    protected final AsyncOpenStackService asyncOpenStackService;

    @Autowired
    public AsyncMultiTaskHandler(AsyncOpenStackService asyncOpenStackService) {
        this.asyncOpenStackService = asyncOpenStackService;
    }

    public void setParameters(Parameter[] parameters){
        this.parameters=parameters;
    }
    public void setCreateParameters(CreateParameter[] createParameters){
        this.createParameters=createParameters;
    }
    public void setWebSocketServlet(String md5, PollWebSocketServlet webSocketServlet) {
        this.md5=md5;
        this.webSocketServlet=webSocketServlet;
    }
    protected void waitTaskDone(List<Future<Map<String,String>>> taskList){
        int taskNumber = taskList.size();
        while (taskNumber>0){
            for(int i=0;i!=taskNumber;++i){
                if(taskList.get(i).isDone()){
                    logger.info("任务"+i+"执行完毕");
                    try {
                        SendMessageUtil.sendMessage(md5,taskList.get(i).get(),webSocketServlet);
                    } catch (ParseException | ExecutionException | InterruptedException e) {
                        e.printStackTrace();
                    }
                    taskList.remove(i);
                    --taskNumber;
                    break;
                }
            }
        }
    }

    @Override
    public void run() {

    }
}
